module address_map(
    input clk,
    input rst_n,

    input [2:0]     data_addr,
    input           data_write_en,
    input           data_read_en,
    input [127:0]     data_write_data,
    output reg [127:0]    data_read_data,

    output [4:0]    CMD,  // wrpckreg  keyexp  staenc stadec
                      //    4        3        2      1  
    output          load,        

    input           keyexprdy,// 密钥扩展状态
    input           encdecrdy, // 加解密状态
    
    // data_path
    output [127:0]  intxt,
    output [127:0]  key,
    input  [127:0]  outtxt
);
    reg [127:0]intxt_r,key_r,outtxt_r;
    reg [7:0]ctrl_r,state;
// 写
    always@(posedge clk or negedge rst_n)begin
        if(!rst_n)begin
            intxt_r  <= 'd0;
            ctrl_r   <= 'd0;
        end
        else if(data_write_en)begin
            if(data_addr == 3'd1)
                ctrl_r <= data_write_data[7:0];
            else if(data_addr == 3'd2)
                intxt_r <= data_write_data;
            else if(data_addr == 3'd3)
                intxt_r   <= data_write_data;
            // else if(data_addr == 3'd4)
            //     outtxt_r <= data_write_data;
        end
        else if(|ctrl_r)
            ctrl_r <= 'd0;
    end

// 读
    always @(posedge clk or negedge rst_n) begin
        if(!rst_n)
            data_read_data <= 'd0;
        else if(data_read_en)begin
            if(data_addr == 3'd0)
                data_read_data <= {120'd0,state};
            else if(data_addr == 3'd1)
                data_read_data <= {120'd0,ctrl_r};
            else if(data_addr == 3'd2)
                data_read_data <= intxt_r;
            else if(data_addr == 3'd3)
                data_read_data <= key_r;
            else if(data_addr == 3'd4)
                data_read_data <= outtxt_r;
        end
    end

    assign CMD = ctrl_r[4:0];
    assign load = ctrl_r[5];

    assign intxt = intxt_r;

    always @(posedge clk or negedge rst_n) begin
        if(!rst_n)
            outtxt_r <= 'd0;
        else
            outtxt_r <= outtxt;
    end
    
    always @(posedge clk or negedge rst_n) begin
        if(!rst_n)
            state[0] <= 1'd0;
        else if(encdecrdy)
            state[0] <= 1'b1;
        else
            state[0] <= 1'b0;
    end

    always @(posedge clk or negedge rst_n) begin
        if(!rst_n)
            state[1] <= 1'd0;
        else if(keyexprdy)
            state[1] <= 1'b1;
        else
            state[1] <= 1'b0;
    end

endmodule